﻿package com.dusk.game
{
	import config.Config;
	
	import flash.display.Loader;
	import flash.display.LoaderInfo;
	import flash.display.MovieClip;
	import flash.events.Event;
	import flash.events.IOErrorEvent;
	import flash.net.URLRequest;
	import flash.system.ApplicationDomain;
	import flash.system.LoaderContext;
	
	public class Debug
	{
		private static const _url:String = "./debugUI.swf";
		private static var _instance:Debug = null;
		
		public static function getIns():Debug
		{
			return _instance;
		}
		
		public function Debug()
		{
			initDebugger();
		}
		
		private var _ui:MovieClip;
		
		/**
		 * 输出日志
		 * @param str 日志内容
		 * @param lv 日志等级，默认为1,0为操作日志，1为游戏日志
		 * 一般直接使用默认即可
		 */
		public function logInfo(str:String,lv:int = 1):void
		{
			if(_ui)
			{
				_ui.log(str,lv);
			}
		}
		
		private function initDebugger():void
		{
			var loader:Loader = new Loader();
			loader.load(new URLRequest(_url), new LoaderContext(false, ApplicationDomain.currentDomain));
			loader.contentLoaderInfo.addEventListener(Event.COMPLETE,function (evt:Event):void
			{
				_ui = (evt.target as LoaderInfo).content as MovieClip;
				_ui["gc"] = Config.getIns();
				(evt.target as LoaderInfo).removeEventListener(Event.COMPLETE, arguments.callee);
				(evt.target as LoaderInfo).removeEventListener(IOErrorEvent.IO_ERROR, arguments.callee);
				changeStageLayout();
				Logger.log("Debugger加载完成");
			});
			loader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, function (evt:Event):void
			{
				(evt.target as LoaderInfo).removeEventListener(Event.COMPLETE, arguments.callee);
				(evt.target as LoaderInfo).removeEventListener(IOErrorEvent.IO_ERROR, arguments.callee);
			});
		}
		
		/**
		 * 改变舞台布局
		 */
		private function changeStageLayout():void
		{
			_instance = this as Debug;
			var game:GMain = GMain.getIns();
			game.stage.stageWidth += 300;
			game.stage.color = 0x999999;
			game.stage.align = "left";
			_ui.x = 940;
			_ui.y = 0;
			game.stage.addChildAt(_ui,0);
			game.relocateWindow();
		}
	}
}